package com.zhxxfwzx.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhxxfwzx.common.lang.RespBean;
import com.zhxxfwzx.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description TODO
 * @title: LoginFailureHandler
 * @Author LiJing
 * @Date: 2021/6/161:04 下午
 * @Version 1.0
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtTokenUtils jwtTokenUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        //生成jwt
        String jwt = jwtTokenUtils.generateToken((UserDetails) authentication.getPrincipal());
        response.setHeader(jwtTokenUtils.getHeader(), jwt);

        PrintWriter out = response.getWriter();
        RespBean ok = RespBean.ok("登录成功", authentication.getPrincipal());
        out.write(new ObjectMapper().writeValueAsString(ok));
        out.flush();
        out.close();
    }
}
